
const { useModel, subscribeModel } = require('../models/index')
const { createJWT } = require('../util/jwt')
const fs = require('fs')
const { promisify } = require('util')
const fsRename = promisify(fs.rename)

//引用lodash
const _ = require('lodash');

/**
 * 
 * @param {*} req 
 * @param {*} res 
 * @description 登录操作操作
 */
const registe = async (req, res) => {

    const registModel = new useModel(req.body)
    try {
        const resulet = await registModel.save()
        if (resulet) {
            const jsonResult = JSON.parse(JSON.stringify(resulet))
            delete jsonResult.password
            res.status(200).json({
                err: 0,
                msg: '注册成功',
                data: jsonResult
            })
        }
    } catch (err) {
        res.status(400).json({
            err: err
        })
    }
}
/**
 * 
 * @param {*} req 
 * @param {*} res 
 * @description 用户的登录操作
 */

const login = async (req, res) => {
    let userInfo = await useModel.findOne(req.body)
    userInfo = userInfo.toJSON()
    const token = await createJWT(userInfo)
    userInfo.token = token
    if (userInfo) {
        res.status(200).json({
            err: 0,
            msg: '登录成功',
            data: userInfo
        })
    } else {
        res.status(404).json({
            err: 1,
            msg: '邮箱或者密码不正确',
        })
    }
}
//用户更新信息
const update = async (req, res) => {

    try {
        //更新用户数据
        const dbback = await useModel.findByIdAndUpdate({ _id }, req.body, { new: true })
        if (dbback) {
            // 更新后返回数据
            res.status(200).json({
                err: 0,
                msg: '修改成功',
                data: dbback
            })
        } else {
            res.status(400).json({
                err: 1,
                msg: '修改失败',
            })
        }
    } catch {
        res.status(400).json({
            err: 1,
            msg: '修改失败',
        })
    }

    res.end()
}

//用户上传头像
const headimage = async (req, res) => {
    const { filename, originalname, destination } = req.file
    const SuffixArr = originalname.split('.')
    const Suffix = SuffixArr[SuffixArr.length - 1]
    const totalfilename = `${filename}.${Suffix}`
    try {
        await fsRename(`${destination}${filename}`, `${destination}${totalfilename}`)
        //获取当前用户的id
        const _id = req.userinfo['_id']
        const useInfo = await useModel.findById(_id)
        //保存当前头像相对路径到数据库
        useInfo.image = `${destination}${totalfilename}`
        await useInfo.save()
        res.status(200).json({
            err: 0,
            msg: '头像上传成功',
            data: `${destination}${totalfilename}`
        })
    } catch {
        res.status(400).json({
            err: 1,
            msg: '头像上传失败',
        })
    }

}
//获取用户列表
const list = async (req, res) => {
    res.send('/list')
}


//订阅频道

const subscribe = async (req, res) => {
    //获取需要关注的用户的id
    let subscribeId = req.params.userId
    if (subscribeId === req.userinfo._id) {
        return res.status(400).json({
            error: 1,
            msg: '抱歉,不能关注自己呢'
        })
    }
    try {
        const channelInfo = await useModel.findById(subscribeId)
        if (!channelInfo) {
            return res.status(400).json({
                error: 1,
                msg: '要关注的用户不存在'
            })
        }
        const subscribeInfo = await subscribeModel.findOne({
            user: req.userinfo._id,
            channel: subscribeId
        })

        if (subscribeInfo) {
            return res.status(400).json({
                error: 1,
                msg: '已经订阅了'
            })
        }
        const subscribe = new subscribeModel({
            user: req.userinfo._id,
            channel: subscribeId
        })
        await subscribe.save()
        channelInfo.subscribecount++
        await channelInfo.save()
        res.status(200).json({
            error: 0,
            msg: '订阅成功',
        })
    } catch (err) {
        return res.status(400).json({
            error: 1,
            msg: err
        })
    }
}
//取消订阅
const unsubscribe = async (req, res) => {
    //获取需要关注的用户的id
    let subscribeId = req.params.userId
    if (subscribeId === req.userinfo._id) {
        return res.status(400).json({
            error: 1,
            msg: '抱歉,不能取消关注自己呢'
        })
    }
    try {
        const channelInfo = await useModel.findById(subscribeId)
        const subscribeInfo = await subscribeModel.findOne({
            user: req.userinfo._id,
            channel: subscribeId
        })
        if (!subscribeInfo) {
            return res.status(400).json({
                error: 1,
                msg: '还未订阅此频道,无法取消订阅'
            })
        } else {
            //删除订阅信息
            await subscribeModel.deleteOne(
                {
                    user: req.userinfo._id,
                    channel: subscribeId
                }
            )
            channelInfo.subscribecount--
            await channelInfo.save()
            res.status(200).json({
                error: 0,
                msg: '取消订阅成功',
            })
        }

    } catch (err) {
        console.log(err)
        return res.status(400).json({
            error: 1,
            msg: err
        })
    }
}

//获取频道信息
const getuser =async (req,res)=>{
    let issubscribe = false
    const _id = req.userinfo._id
    const channelid = req.params.userId
    const record =await subscribeModel.findOne({
        user:_id,
        channel:channelid
    })
    console.log('record',record)
    if(record){
        issubscribe = true
    }
    let userinfo =await useModel.findById(channelid)
    userinfo = _.pick(userinfo, ['_id','name', 'subscribecount','image']);
    res.status(200).json({
        error: 0,
        msg: '获取成功',
        data:{
            ...userinfo,
            issubscribe
        }
    })
}

//获取当前用户的粉丝列表（谁关注了我）
const getchannel =async (req,res)=>{
    const _id = req.userinfo._id
    let dbback =await subscribeModel.find({
        channel:_id
    }).populate('user','_id name image subscribecount')
    dbback = dbback.map((item)=>{
        return item.user
    })
    res.status(200).json({
        error: 0,
        msg: '获取粉丝列表成功',
        data:dbback
    })
}

//获取关注的是谁
const getsubscribe =async (req,res)=>{
    const _id = req.params.userId
    let dbback =await subscribeModel.find({
        user:_id
    }).populate('channel','_id name image subscribecount')
    dbback = dbback.map((item)=>{
        return item.channel
    })
    res.status(200).json({
        error: 0,
        msg: '获取关注列表成功',
        data:dbback
    })
    res.end()
}


module.exports = {
    registe,
    login,
    update,
    headimage,
    list,
    subscribe,
    unsubscribe,
    getuser,
    getchannel,
    getsubscribe
}